$(function () {
    // 页面初始化生成验证码
    createCode('#loginCode');
    // 验证码切换
    $('#loginCode').click(function () {
        createCode('#loginCode');
    });
    // 登陆事件
    $('#loginBtn').click(function () {
        login();
    });
});
// 生成验证码
function createCode(codeID) {
    let code = "";
    // 验证码长度
    let codeLength = 4;
    // 验证码dom元素
    let checkCode = $(codeID);
    // 验证码随机数
    let random = [2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
        'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for (let i = 0; i < codeLength; i++){
        // 随机数索引
        let index = Math.floor(Math.random() * 32);
        code += random[index];
    }
    // 将生成的随机验证码赋值
    checkCode.val(code);
}
// 校验验证码、用户名、密码
function validateCode(inputID,codeID) {
    let inputCode = $(inputID).val().toUpperCase();
    let cardCode = $(codeID).val();
    let loginUsername = $('#loginUsername').val();
    let loginPassword = $('#loginPassword').val();
    if ($.trim(loginUsername) === '' || $.trim(loginUsername).length<=0){
        layer.alert("用户名不能为空");
        createCode('#loginCode');
        return false;
    }
    if ($.trim(loginPassword) === '' || $.trim(loginPassword).length<=0){
        layer.alert("密码不能为空");
        createCode('#loginCode');
        return false;
    }
    if (inputCode.length<=0){
        layer.alert("验证码不能为空");
        createCode('#loginCode');
        return false;
    }
    if (inputCode !== cardCode){
        layer.alert("请输入正确验证码");
        createCode('#loginCode');
        return false;
    }
    return true;
}
// 登录流程
function login() {
    if (!validateCode('#loginCard','#loginCode')){
        //阻断提示
        return;
    }

    let loginUsername = encrypt($('#loginUsername').val());
    let loginPassword = encrypt($('#loginPassword').val());

    $.ajax({
        url: contextPath+ "/ctrl/login/doLogin",
        type: 'post',
        data: {"loginName": loginUsername,"password":loginPassword},
        success: function(data){
            data = data.data;
            if(data.result){
                localStorage.setItem("star_token",data.token);
                if(data.userType==="0"){
                    layer.alert("普通用户")
                }else{
                    var url = contextPath+"/ctrl/manager/index?star_token="+data.token;
                    window.location.href=url;
                }
            }else{
                layer.alert("登录失败！");
            }
        }
    });

}

function encrypt(value){
    var publicKey = $("#publicKey").val();
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    value = encrypt.encrypt(value) ;
    return value ;
}